<template>
	<view class="wrap">
		<view class="list-wrap">
			<movable-area class="movable-area-wrap" :style="{
				height:eventList.length*42+'px'
			}">
				<movable-view class="moveable-item" direction="vertical" v-for="(item,index) in showList"
					:key="item.eventId" @touchend="touchEnd" @touchstart="touchStart(index)"
					@change="viewChange($event,index)" :y="item.y">
					<list-item :title="item.eventName" :changeType="item.changeType" :amount="item.amount" />
				</movable-view>
			</movable-area>
		</view>
		<uni-fab horizontal="right" vertical="bottom" :popMenu="false" @fabClick="fabClick" />
		<uni-popup ref="popup" background-color="#fff">
			<event-add-form @submit="submit" />
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
	import { nextTick, reactive, ref, watch } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import moment from 'moment';
	import { addDateRecord, addEventRecord, queryDateId, queryEventRecord, exchangeEventWeight } from '../../indexDB';

	import { DB } from '../../indexDB/DBType';
	import eventAddForm from "../../components/EventAddForm.vue";
	import listItem from "../../components/ListItem.vue";
	type ShowItem = DB.EventRecordSource & { y : number };
	const nowDate = moment().format('YYYY-MM-DD');
	const dateId = ref(0);
	const eventList = ref<Array<DB.EventRecordSource>>([]);
	const showList = ref<Array<ShowItem>>([]);
	watch(eventList, (data) => {
		showList.value = data.map((v, i) => ({
			...v,
			y: i * 42
		}))
	})
	const popup = ref(null);
	const fabClick = () => {
		popup.value?.open('top');
	}
	const indexParam = reactive({
		currentIndex: 0,
		targetIndex: 0,
		idList: [0],
		vList: {} as Record<number, ShowItem>,
	})
	const activeIndex = ref(0);
	const viewChange = (e : any) => {
		if (e.detail.source !== 'touch') return;
		const y = e.detail.y;
		const target = Math.round(y / 42);
		const current = activeIndex.value;
		const { vList } = indexParam;
		vList[current].y = e.detail.y;
		if (target === current) return;
		vList[target].y = current * 42;
		const currentItem = vList[current];
		vList[current] = vList[target];
		vList[target] = currentItem;
		activeIndex.value = target;
		indexParam.targetIndex = target;

	}
	const touchStart = (index : number) => {
		indexParam.currentIndex = index;
		indexParam.targetIndex = index;
		activeIndex.value = index;
		indexParam.idList = eventList.value.map(v => v.eventId);
		indexParam.vList = showList.value.reduce((t, v, i) => {
			t[i] = v;
			return t;
		}, {});
	}
	const touchEnd = () => {
		const index = activeIndex.value;
		const { vList, currentIndex, targetIndex, idList } = indexParam;
		if (currentIndex === targetIndex) {
			setTimeout(() => {
				vList[index].y = 42 * index;
			}, 0)
		} else {
			const indexArr = [currentIndex, targetIndex];
			const startEventId = idList[Math.min(...indexArr)];
			const endEventId = idList[Math.max(...indexArr)];
			changeEventRecord({ startEventId, endEventId })
		}

	}
	const lock = ref(false);
	const changeEventRecord = async (params : { startEventId : number; endEventId : number; }) => {
		if (lock.value) return;
		lock.value = true;
		await exchangeEventWeight({
			dateId: dateId.value,
			...params
		});
		await querAllEvent()
		lock.value = false;
	}
	const querAllEvent = async () => {
		if (!dateId.value) return;
		const res = await queryEventRecord({ dateId: dateId.value })
		eventList.value = res.data;
		popup.value?.close();
	}
	const submit = async (data : DB.EventRecord) => {
		await addEventRecord({ dateId: dateId.value, ...data });
		querAllEvent();
	}
	// query是url参数 ，第一位形参为query
	onLoad(async () => {
		const res = await queryDateId({ date: nowDate });
		if (res.data) {
			dateId.value = res.data
		} else {
			const addRes = await addDateRecord({ date: nowDate });
			dateId.value = addRes.data as number;
		}

		querAllEvent();
	})
</script>

<style lang="scss" scoped>
	.wrap {
		padding: 15px;

		.list-wrap {
			background-color: #ffffff;
		}
	}

	.movable-area-wrap {
		width: 100%;
	}

	.moveable-item {
		width: 100%;
		height: 42px;
	}

	.list-item {
		height: 100%;
		width: 100%;
		box-sizing: border-box;
		color: #ffffff !important;

		&.expend {
			background-color: rgba(253, 224, 71, 0.8) !important;
		}

		&.income {
			background-color: rgba(163, 230, 53, 0.8) !important;
		}
	}
</style>